﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Quickly.SpaProxy.ReverseProxy;

public static class SpaReverseProxyBuilderExtensions
{
    public static IServiceCollection AddSpaReverseProxy(this IServiceCollection services)
    {
        // spa proxy config file 
        var spaProxyConfigFile = Path.Combine(AppContext.BaseDirectory, "quickly.spa.proxy.json");

        if (File.Exists(spaProxyConfigFile))
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile(spaProxyConfigFile)
                .Build();

            services.AddCors(setup =>
            {
                setup.AddPolicy("DevAllowAnyOrigin", policy => policy.AllowAnyOrigin());
            });

            services.AddReverseProxy()
                .LoadFromConfig(configuration.GetSection("ReverseProxy"))
                .LoadFromSpaProxy(configuration.GetSection("SpaProxyServer"));
        }

        return services;
    }
}
